package com.wanlian.socketserver.Device;


import com.wanlian.netty.File.msg.FilePeerMsgDecoder;
import com.wanlian.netty.File.msg.FilePeerMsgEncoder;
import com.wanlian.netty.msg.PeerMsgDecoder;
import com.wanlian.netty.msg.PeerMsgEncoder;
import com.wanlian.socketserver.Device.Handler.DeviceServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DeviceServer {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private int port;
    private String publicKey;
    public ServerSocketChannel socketChannel;

    public DeviceServer(int port) {
        this.port = port;
    }

    public DeviceServer(int port, String publicKey) {
        this.port = port;
        this.publicKey = publicKey;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        // try {
        ServerBootstrap b = new ServerBootstrap(); // (2)
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3)
                .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.TCP_NODELAY, true)
                .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new PeerMsgDecoder());
                        p.addLast(new PeerMsgEncoder());
                        p.addLast(new DeviceServerHandler());
                    }
                });
        ChannelFuture f = b.bind(port).sync(); // (7)
        logger.info("server bind port:{}", port);
        if (f.isSuccess()) {
            socketChannel = (ServerSocketChannel) f.channel();
        }
    }

    public String getPublicKey() {
        return publicKey;
    }

    public void setPublicKey(String publicKey) {
        this.publicKey = publicKey;
    }
}
